package com.gateWay.filters;

import com.gateWay.properties.AuthProperties;
import com.gateWay.properties.JwtProperties;
import com.sky.constant.JwtClaimsConstant;
import com.sky.context.BaseContext;
import com.sky.utils.JwtUtil;
import io.jsonwebtoken.Claims;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.Ordered;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.List;


@Component
@EnableConfigurationProperties(AuthProperties.class)
@RequiredArgsConstructor
@Slf4j
public class AuthGlobalFilter implements GlobalFilter, Ordered {

    private final AuthProperties authProperties;
    private final AntPathMatcher antPathMatcher=new AntPathMatcher();
    private final JwtProperties jwtProperties;
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //1.获取请求头
        ServerHttpRequest request = exchange.getRequest();

        //2.获取请求头中的路径 判断是否需要拦截
        if(isExclude(request.getPath().toString())){
            //直接放行
        return chain.filter(exchange);
        }
        //解析token
        String tokenAdmin=null,tokenUser=null;
        List<String> list1=request.getHeaders().get(jwtProperties.getAdminTokenName());
        List<String> list2=request.getHeaders().get(jwtProperties.getUserTokenName());
        if(list1!=null)tokenAdmin=list1.get(0);
        if(list2!=null)tokenUser=list2.get(0);
        //2、校验令牌
        Long id=null;
        try {
            String token="",secretKey="",name="";
            if(tokenAdmin!=null&&!tokenAdmin.equals("")){
                token=tokenAdmin;
                secretKey= jwtProperties.getAdminSecretKey();
                name=JwtClaimsConstant.EMP_ID;
            }
            if(tokenUser!=null&&!tokenUser.equals("")){
                token=tokenUser;
                secretKey= jwtProperties.getUserSecretKey();
                name=JwtClaimsConstant.USER_ID;
            }
            log.info("jwt校验:{}", token);
            Claims claims = JwtUtil.parseJWT(secretKey, token);
            id= Long.valueOf(claims.get(name).toString());
        } catch (Exception ex) {
            //3、不通过，响应401状态码
            //没有登录过进行拦截 返回前端未授权的信息 通过上下文的返回体返回
            ServerHttpResponse response = exchange.getResponse();
            response.setRawStatusCode(401);
            return response.setComplete();
        }
        //3.保存用户信息到请求头
        String userInfo = id.toString();//保存用户信息到请求头中
        ServerWebExchange ex = exchange.mutate().request(b -> b.header("user-info", userInfo)).build();
        //System.out.println("userId:"+userId);
        //放行
        return chain.filter(ex);//执行下一个过滤链 上下文信息传给下一个过滤连
    }

    @Override
    public int getOrder() {
        return 0;
    }

    private boolean isExclude(String path){
         List<String> excludePaths=authProperties.getExcludePaths();
         for(String excludePath:excludePaths){
             if(antPathMatcher.match(excludePath,path)){
                 return true;
             }
         }
         return false;
    }
}
